package com.anolesoft.yr.mbus.contm.ctrl;

import cn.hutool.core.util.StrUtil;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.common.core.web.page.TableDataInfo;
import com.anolesoft.system.fac.entity.Employee;
import com.anolesoft.system.fac.service.IEmployeeService;
import com.anolesoft.yr.mbus.cont.entity.ContVariable;
import com.anolesoft.yr.mbus.cont.entity.PageType;
import com.anolesoft.yr.mbus.contm.dto.ContmBaseClauseDto;
import com.anolesoft.yr.mbus.contm.dto.ContmContentDto;
import com.anolesoft.yr.mbus.contm.dto.ContmMainDto;
import com.anolesoft.yr.mbus.contm.entity.*;
import com.anolesoft.yr.mbus.contm.service.ContmContentService;
import com.anolesoft.yr.mbus.contm.service.ContmCreateService;
import com.anolesoft.yr.mbus.contm.service.ContmMainService;
import com.anolesoft.yr.store.stk.util.StringUtil;
import com.anolesoft.yr.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/contm/contm_main")
@AllArgsConstructor
public class ContmMainController {

    private ContmContentService contmContentService;
    private ContmMainService contmMainService;
    private IEmployeeService iEmployeeService;

        @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
        public AjaxResult add(@RequestBody ContmMainDto contmMainDto){
            String username = SecurityUtils.getLoginUser().getEmpUid();
            String objuid = StringUtil.generateRundom32String();
            ContmMain contmMain = ContmMain.builder()
                    .cUserUid(username)
                    .contTypeUid(contmMainDto.getContType())
                    .cTime(new Date())
                    .remark(contmMainDto.getRemark())
                    .objuid(objuid)
                    .contName(contmMainDto.getContName())
                    .styleMainUid(contmMainDto.getContmStyleMainUid())
                    .build();
            List<ContmContentDto> contmContentDtos = contmMainDto.getContmContentDtos();
            List<ContmContent> contmContents = Lists.newArrayList();
            for (int i = 0; i < contmContentDtos.size(); i++) {
                ContmContentDto contmContentDto = contmContentDtos.get(i);
                contmContents.addAll(contmContentDto.toContmContent(objuid));
            }
            for (int i = 0; i < contmContents.size(); i++) {
                contmContents.get(i).setParentUid("");
                contmContents.get(i).setOrderCode(Byte.parseByte(Integer.toString(i)));
            }
            contmContentService.pageInsertBatch(contmContents);
            contmMainService.save(contmMain);
            return AjaxResult.success();
        }

    @Transactional
    @RequestMapping(value = "/get", produces = {"application/json;charset=UTF-8"})
    public AjaxResult get(ContmMain contmMain){
        Page<ContmMain> page = new Page<>(contmMain.getPage(), contmMain.getRows());
        String contName = StrUtil.nullToEmpty(contmMain.getContName());
        LambdaQueryWrapper<ContmMain> like = new QueryWrapper<ContmMain>()
                .lambda()
                .like(ContmMain::getContName, contName)
                .orderByDesc(ContmMain::getcTime);

        Page<ContmMain> result = contmMainService.page(page, like);
        LambdaQueryWrapper<Employee> emplike = new QueryWrapper<Employee>()
                .lambda();
        List<Employee> employees = iEmployeeService.getBaseMapper().selectList(emplike);
        Map<String, String> collect = employees.stream().collect(Collectors.toMap(Employee::getObjuid, Employee::getEmpName));


        System.out.println(collect);
        List<ContmMain> records = result.getRecords();

        for (int i = 0; i < records.size(); i++) {
            if(records.get(i).getcUserUid()!=null){
                records.get(i).setcUserUid(collect.get(records.get(i).getcUserUid()));
            }
        }
        return AjaxResult.success(new TableDataInfo(        result.getTotal(),   records    ));
    }
    @Transactional
    @RequestMapping(value = "/getForEdit", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getForEdit(ContmMain contmMain){
        ContmContentExample contmContentExample = new ContmContentExample();
        contmContentExample.setOrderByClause("order_code");
        contmContentExample.createCriteria().andContmMainUidEqualTo(contmMain.getObjuid());
        List<ContmContent> contmContents = contmContentService.selectByExample(contmContentExample);
        List<ContmContentDto> contmContentDtos = contmContents.stream().map(a -> a.toContmContentDto()).collect(Collectors.toList());
        for (int i = 0; i < contmContentDtos.size(); i++) {
            if (contmContentDtos.get(i).getType().equals("nr")){
                for (int j = 0; j < contmContentDtos.size() ; j++) {
                    if (contmContentDtos.get(j).getId().equals(contmContentDtos.get(i).getPId())){
                        contmContentDtos.get(j).setContent(contmContentDtos.get(i).getTitle());
                    }
                }
            }
        }
        contmContentDtos=contmContentDtos.stream().filter(a->a.getType().equals("bt")).collect(Collectors.toList());
        List<String> titles = Lists.newArrayList(PageType.FIRST_PAGE,PageType.SECOND_PAGE,PageType.MAKE_PAGE,PageType.CONTENT_PAGE,PageType.SIGN_PAGE,PageType.LAST_PAGE);
        List <ContmContentDto>titleDto = Lists.newArrayList();

        for (int i = 0; i < titles.size(); i++) {
            titleDto.add(ContmContentDto.builder().id(Integer.toString(i)).name(titles.get(i)).pId("").ppId("").build());
        }
        Map<String, String> parentMap = titleDto.stream().collect(Collectors.toMap(ContmContentDto::getName, ContmContentDto::getId));
        for (int i = 0; i < contmContentDtos.size(); i++) {
            ContmContentDto contmContentDto = contmContentDtos.get(i);
            if (contmContentDto.getPpId() == null ||contmContentDto.getPpId().equals("")){
                contmContentDto.setPId(parentMap.get(contmContentDto.getPageType()));
                contmContentDto.setPpId(parentMap.get(contmContentDto.getPageType()));
            }
        }
        contmContentDtos.addAll(titleDto);
        ContmMain result = contmMainService.getById(contmMain.getObjuid());
        ContmMainDto build = ContmMainDto.builder().contmContentDtos(contmContentDtos).contName(result.getContName()).remark(result.getRemark()).contmStyleMainUid(result.getStyleMainUid()).build();
        return AjaxResult.success(build);
    }

    @Transactional
    @RequestMapping(value = "/edit", produces = {"application/json;charset=UTF-8"})
    public AjaxResult edit(@RequestBody ContmMainDto contmMainDto){
        String username = SecurityUtils.getLoginUser().getEmpUid();
        String objuid = contmMainDto.getObjuid();
        ContmMain contmMain = ContmMain.builder()
                .cUserUid(username)
                .contTypeUid(contmMainDto.getContType())
                .cTime(new Date())
                .remark(contmMainDto.getRemark())
                .objuid(objuid)
                .contName(contmMainDto.getContName())
                .styleMainUid(contmMainDto.getContmStyleMainUid())
                .build();

        ContmMainExample contmMainExample = new ContmMainExample();
        contmMainExample.createCriteria().andObjuidEqualTo(objuid);
        List<ContmContentDto> contmContentDtos = contmMainDto.getContmContentDtos();
        List<ContmContent> contmContents = Lists.newArrayList();
        for (int i = 0; i < contmContentDtos.size(); i++) {
            ContmContentDto contmContentDto = contmContentDtos.get(i);
            contmContents.addAll(contmContentDto.toContmContent(objuid));
        }
        for (int i = 0; i < contmContents.size(); i++) {
            contmContents.get(i).setParentUid("");
            contmContents.get(i).setOrderCode(Byte.parseByte(Integer.toString(i)));
        }
        ContmContentExample contmContentExample = new ContmContentExample();
        contmContentExample.createCriteria().andContmMainUidEqualTo(objuid);
        contmContentService.deleteByExample(contmContentExample);
        contmContentService.pageInsertBatch(contmContents);
        contmMainService.updateByExampleSelective(contmMain,contmMainExample);
        return AjaxResult.success("修改成功");
    }

    @RequestMapping(value = "/selectList", produces = {"application/json;charset=UTF-8"})
    public List<ContmMain> selectList(){
        return contmMainService.selectByExample(new ContmMainExample());

    }

    @Transactional
    @RequestMapping(value = "/delbatch", produces = {"application/json;charset=UTF-8"})
    public AjaxResult delbatch(@RequestBody List<ContmMain> contmMains) {
        List<String> collect = contmMains.stream().map(ContmMain::getObjuid).collect(Collectors.toList());
        contmMainService.removeByIds(collect);
        return AjaxResult.success("删除成功");
    }
}
